import { useAuthStore } from '@/store/authStore'

type RequestConfig = {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: Record<string, string>
  timeout?: number
}

const request = (config: RequestConfig) => {
  // 请求拦截
  const authStore = useAuthStore()
  const header = {
    ...config.header,
    'Cache-Control': 'no-cache',
    ...(authStore.token ? { 'Authorization': `Bearer ${authStore.token}` } : {})
  }

  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      header,
      url: config.url.startsWith('/mock/api') ? config.url : (import.meta as any).env.VITE_API_BASE_URL + config.url,
      timeout: config.timeout || 10000,
      success: (res) => {
        // 响应拦截
        if (res.statusCode !== 200) {
          uni.showToast({ title: '网络请求失败', icon: 'none' })
          return reject(new Error('网络请求失败'))
        }
        
        const data = res.data
        // 检查 data 是否为对象且包含 code 属性
        if (typeof data === 'object' && data !== null && 'code' in data && data.code !== 200) {
          uni.showToast({ title: data.message || '请求失败', icon: 'none' })
          return reject(new Error(data.message || 'Error'))
        }
        resolve(data)
      },
      fail: (err) => {
        uni.showToast({ title: err.errMsg || '网络异常', icon: 'none' })
        reject(err)
      }
    })
  })
}

export default request